package com.test2015.Swing.ext.ipfield;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;

public class MacField extends JPanel{
	private MacField thisfield = this;
	private String strMac = null;
	private long longMac = 0;
	private JLabel[] colons = new JLabel[5];	
	private JTextField[] macs = new JTextField[6];	
	private Border fieldBorder = new JTextField().getBorder();
	private boolean isFocus = false;
	
	public MacField(String strMac){
		this.strMac = strMac;
		longMac = getLongMacByStrMac(strMac);
		
		this.setMinimumSize(new Dimension(170,28));
		
		initUI();
		this.setBackground(Color.WHITE);
		this.setBorder(fieldBorder);
	}
	
	
	private void initUI() {
		MyFocusLintener myFocusLintener = new MyFocusLintener();
		for(int i=0;i<macs.length;i++){
			macs[i] = new JTextField("FF");
			macs[i].setBorder(null);
			this.add(macs[i]);
			macs[i].addFocusListener(myFocusLintener);
			
			if(i!=5){
				colons[i] = new JLabel(":");
				this.add(colons[i]);
			}
		}
	}	
	
	@Override
	protected void paintChildren(Graphics g) {
		reSizeChilds();
		this.doLayout();
		super.paintChildren(g);
	}
	
	public void reSizeChilds(){
		Dimension psize = this.getPreferredSize();
		Dimension size = this.getSize();
		int w = Math.max(psize.width, size.width);
		int h = Math.max(psize.height, size.height)-14;
		int avgw = w/25;
		
		for(int i =0;i<colons.length;i++){
			colons[i].setPreferredSize(new Dimension(avgw,h));
			macs[i].setPreferredSize(new Dimension(avgw*2,h));
		}
		macs[5].setPreferredSize(new Dimension(avgw*2,h));
	}
	
	private long getLongMacByStrMac(String strMac2) {
		return 0;
	}
	
	class MyFocusLintener implements FocusListener {

		public void focusGained(FocusEvent focusevent) {
			if(!isFocus){
				thisfield.setBorder(BorderFactory.createLineBorder(Color.red));
				isFocus = true;
			}
		}

		public void focusLost(FocusEvent focusevent) {
			boolean flag = true;
			for(int i=0;i<macs.length;i++){
				boolean hasFocus = macs[i].hasFocus();
				if(!hasFocus){
					continue;
				}else{
					flag = false;
					break;
				}
			}
			if(flag){
				thisfield.setBorder(fieldBorder);
				isFocus = false;
			}
		}
	}
}


